#include <iostream>
using namespace std;
#include <assert.h>
#include <pthread.h>
#include <unistd.h>
#include <mutex>
#include <vector>
#include <string>

int tickets = 10000;
class ThreadData
{
public:
    ThreadData(const string &threadname)
        : _thread_name(threadname), _lock(nullptr)
    {
    }
    ~ThreadData()
    {
    }

public:
    string _thread_name;
    pthread_mutex_t *_lock;
};

void *get_tickets(void *args)
{
    ThreadData *ret = static_cast<ThreadData *>(args);
    while (1)
    {
        pthread_mutex_lock(ret->_lock);
        if (tickets > 0)
        {
            //usleep(124);
            cout << ret->_thread_name << "正在抢票" << tickets << endl;
            tickets--;
            pthread_mutex_unlock(ret->_lock);
        }
        else
        {
            pthread_mutex_unlock(ret->_lock);

            break;
        }
    }
    return nullptr;
}

int main()
{
    pthread_mutex_t lock;
    pthread_mutex_init(&lock, nullptr);

    vector<pthread_t> tds(5);
    for (int i = 1; i <= 5; i++)
    {
        char buffer[128];
        snprintf(buffer, sizeof(buffer), "thread %d", i);
        ThreadData *ret = new ThreadData(buffer);
        pthread_create(&tds[i], nullptr, get_tickets, ret);
    }

    for (auto e : tds)
    {
        pthread_join(e, nullptr);
    }

    return 0;
}